package com.jfinal_demo.app.controllers;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal_demo.app.DataWrapper;
import com.jfinal_demo.app.authenticate.LoginInfo;
import com.jfinal_demo.app.services.ArticalService;

public class ArticalController extends BaseController {
    private final ArticalService articalService = enhance(ArticalService.class);

    @Before(GET.class)
    public void list() {
        Long tagId = getParaToLong("tagId");
        getPageInfo();
        renderJson(articalService.list(tagId, pageNumber, pageSize));
    }

    @Before(POST.class)
    public void createArtical() {
        String title = getPara("title");
        String content = getPara("content");
        long tagId = getParaToLong("tagId");

        LoginInfo loginInfo = getLoginInfo();
        if (loginInfo == null) throw new RuntimeException("请先登录");

        renderJson(articalService.createArtical(title, content, tagId, loginInfo.getUserId()));
    }

    @Before(POST.class)
    public void modifyArtical() {
        long id = getParaToLong("id");
        String title = getPara("title");
        String content = getPara("content");
        long tagId = getParaToLong("tagId");

        LoginInfo loginInfo = getLoginInfo();
        if (loginInfo == null) throw new RuntimeException("请先登录");

        articalService.modifyArtical(id, title, content, tagId, loginInfo.getUserId());
        succeed();
    }

    public void deleteArtical() {
        Long tagId = getParaToLong("tagId");
        renderJson(articalService.deleteArtical(tagId) ? new DataWrapper() : DataWrapper.fail("failed"));
    }
}
